import pygame
from .constants import *
from game.player import Player
from game.game_mode import RobotDifficulty


class Renderer:
    def __init__(self, screen):
        self.screen = screen
        self.font = self._load_chinese_font(24)
        self.large_font = self._load_chinese_font(48)

    def _load_chinese_font(self, size):
        # 加载中文字体
        import platform

        # 获取系统所有可用字体
        all_fonts = pygame.font.get_fonts()
        system = platform.system().lower()

        # 根据操作系统设置中文字体关键词列表（按优先级排序）
        if system == "windows":
            chinese_keywords = [
                'microsoftyahei', 'msyh',           # 微软雅黑
                'simhei',                            # 黑体
                'simsun', 'nsimsun',                # 宋体
                'kaiti', 'simkai',                  # 楷体
                'fangsong', 'simfang',              # 仿宋
                'lishu', 'simli',                   # 隶书
                'yuan', 'simyou',                   # 圆体
                'noto', 'droid', 'wenquanyi',       # 跨平台字体
                'pingfang', 'heiti', 'songti',      # macOS/Linux字体
                'yahei'
            ]
        elif system == "darwin":  # macOS
            chinese_keywords = [
                'pingfang', 'heiti', 'songti',     # macOS系统字体
                'noto', 'droid', 'wenquanyi',      # 跨平台字体
                'kaiti', 'fang',
                'microsoft', 'yahei', 'simsun'     # 备用
            ]
        else:  # Linux及其他系统
            chinese_keywords = [
                'noto', 'wenquanyi', 'droid',      # Linux常用中文字体
                'wqy', 'source', 'arphic',         # 文泉驿/思源字体
                'pingfang', 'heiti', 'songti',     # 备用
                'kaiti', 'fang',
                'microsoft', 'yahei', 'simsun'     # 备用
            ]

        # 查找包含中文字体关键词的字体
        chinese_fonts = []
        for font_name in all_fonts:
            font_lower = font_name.lower()
            for keyword in chinese_keywords:
                if keyword in font_lower:
                    chinese_fonts.append(font_name)
                    break

        # 更严格的字体测试方法
        def _test_chinese_rendering(font, test_text="测试"):
            # 测试字体显示
            try:
                surface = font.render(test_text, True, (0, 0, 0))
                # 检查渲染结果是否合理
                if surface.get_width() > 0 and surface.get_height() > 0:
                    # 额外检查：确保字符有实际的渲染内容（不是空白）
                    return True
            except Exception:
                pass
            return False

        # 按优先级尝试加载中文字体
        for font_name in chinese_fonts:
            try:
                font = pygame.font.SysFont(font_name, size)
                if _test_chinese_rendering(font):
                    print(f"成功加载中文字体: {font_name}")
                    return font
            except Exception as e:
                print(f"尝试加载字体 {font_name} 失败: {e}")
                continue

        # 如果所有中文字体都失败，尝试常见系统字体
        common_fonts = ['arial', 'timesnewroman', 'couriernew'] if system == "windows" else ['arial', 'times']
        for font_name in common_fonts:
            if font_name in all_fonts:
                try:
                    font = pygame.font.SysFont(font_name, size)
                    print(f"使用系统默认字体: {font_name}")
                    return font
                except:
                    continue

        # 最后的回退选项：使用pygame默认字体
        print("警告：无法找到合适的中文字体，使用默认字体")
        return pygame.font.Font(None, size)

    def draw_board(self):
        self.screen.fill(BOARD_COLOR)

        for i in range(BOARD_SIZE):
            start_x = MARGIN + i * CELL_SIZE
            start_y = MARGIN
            end_y = MARGIN + (BOARD_SIZE - 1) * CELL_SIZE
            pygame.draw.line(self.screen, LINE_COLOR, (start_x, start_y), (start_x, end_y), 1)

            start_x = MARGIN
            start_y = MARGIN + i * CELL_SIZE
            end_x = MARGIN + (BOARD_SIZE - 1) * CELL_SIZE
            pygame.draw.line(self.screen, LINE_COLOR, (start_x, start_y), (end_x, start_y), 1)

        star_points = [(3, 3), (3, 11), (11, 3), (11, 11), (7, 7)]
        for row, col in star_points:
            x = MARGIN + col * CELL_SIZE
            y = MARGIN + row * CELL_SIZE
            pygame.draw.circle(self.screen, LINE_COLOR, (x, y), 5)

    def draw_stones(self, board):
        for row in range(BOARD_SIZE):
            for col in range(BOARD_SIZE):
                stone = board.get_stone(row, col)
                if stone != 0:
                    x = MARGIN + col * CELL_SIZE
                    y = MARGIN + row * CELL_SIZE
                    color = BLACK_STONE if stone == Player.BLACK.value else WHITE_STONE
                    pygame.draw.circle(self.screen, color, (x, y), STONE_RADIUS)

                    if board.last_move and board.last_move == (row, col):
                        pygame.draw.circle(self.screen, LAST_MOVE_MARK, (x, y), 5)

    def draw_status(self, game):
        board_bottom = MARGIN + (BOARD_SIZE - 1) * CELL_SIZE + 20
        use_llm = game.game_mode.name == "PVC" and game.robot_difficulty == RobotDifficulty.OPENAI

        if game.state.name == "ROBOT_THINKING":
            text = "大模型正在思考..." if use_llm else "机器人正在思考..."
        elif game.state.name == "PLAYING":
            if game.game_mode.name == "PVC":
                if game.current_player.name == "BLACK":
                    text = "轮到你了"
                else:
                    text = "轮到大模型" if use_llm else "轮到机器人"
            else:
                text = f"当前玩家: {game.current_player}"
        else:
            winner = game.get_winner()
            if game.game_mode.name == "PVC":
                if winner.name == "BLACK":
                    text = "你赢了!"
                else:
                    text = "大模型赢了!" if use_llm else "机器人赢了!"
            else:
                text = f"{winner} 获胜!"

        text_surface = self.large_font.render(text, True, TEXT_COLOR)
        text_rect = text_surface.get_rect(center=(WINDOW_WIDTH // 2, board_bottom + 20))
        self.screen.blit(text_surface, text_rect)

        # 显示游戏模式和难度信息
        mode_text = f"模式: {game.game_mode.value}"
        if game.game_mode.name == "PVC":
            mode_text += f" (机器人: {game.robot_difficulty.value})"

        mode_surface = self.font.render(mode_text, True, TEXT_COLOR)
        mode_rect = mode_surface.get_rect(center=(WINDOW_WIDTH // 2, board_bottom + 60))
        self.screen.blit(mode_surface, mode_rect)

    def draw_button(self, rect, text, mouse_pos):
        color = BUTTON_HOVER if rect.collidepoint(mouse_pos) else BUTTON_COLOR
        pygame.draw.rect(self.screen, color, rect, border_radius=5)

        text_surface = self.font.render(text, True, TEXT_COLOR)
        text_rect = text_surface.get_rect(center=rect.center)
        self.screen.blit(text_surface, text_rect)

    def draw_buttons(self, reset_btn, undo_btn, menu_btn, mouse_pos):
        self.draw_button(reset_btn, "重新开始", mouse_pos)
        self.draw_button(undo_btn, "悔棋", mouse_pos)
        self.draw_button(menu_btn, "菜单", mouse_pos)

    def get_board_pos(self, mouse_x, mouse_y):
        if mouse_x < MARGIN - CELL_SIZE // 2 or mouse_x > MARGIN + (BOARD_SIZE - 1) * CELL_SIZE + CELL_SIZE // 2:
            return None, None
        if mouse_y < MARGIN - CELL_SIZE // 2 or mouse_y > MARGIN + (BOARD_SIZE - 1) * CELL_SIZE + CELL_SIZE // 2:
            return None, None

        col = round((mouse_x - MARGIN) / CELL_SIZE)
        row = round((mouse_y - MARGIN) / CELL_SIZE)

        if 0 <= row < BOARD_SIZE and 0 <= col < BOARD_SIZE:
            return row, col

        return None, None
